package com;

import java.util.HashMap;
import java.util.Map;

import io.netty.channel.Channel;
import io.netty.channel.ChannelId;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.ImmediateEventExecutor;
import lombok.extern.slf4j.Slf4j;

/**
 * 保存群组
 */
@Slf4j
public class ChannelGroupHolder {

    private static Map<String, ChannelGroup> channelGroups = new HashMap<>();
    private static Map<String, String> channelTagMapping = new HashMap<>();

    public static Map<String, ChannelGroup> getChannelGroups() {
        return channelGroups;
    }

    /**
     * 添加channel到群组
     */
    public static synchronized void add(String tag, Channel channel) {
        ChannelGroup group = channelGroups.get(tag);
        if (group == null) {
            group = new DefaultChannelGroup(ImmediateEventExecutor.INSTANCE);
            log.info("创建新群组：{}", tag);
            channelGroups.put(tag, group);
        }
        group.add(channel);
        ChannelId channelId = channel.id();
        channelTagMapping.put(channelId.toString(), tag);
        log.info("群组{}加入新channel：{}", tag, channelId);
    }

    /**
     * 根据IP获取群组
     */
    public static ChannelGroup get(String tag) {
        return channelGroups.get(tag);
    }

    /**
     * 移除指定channel，如果群组变为空，返回对应IP
     */
    public static String remove(Channel channel) {
        String channelId = channel.id().toString();
        String tag = channelTagMapping.get(channelId);
        channelTagMapping.remove(channelId);
        if (tag != null && !channelTagMapping.containsValue(tag)) {
            log.info("移除channel：{}，所在群组：{}", channelId, tag);
            return tag;
        }
        return null;
    }

    /**
     * 关闭所有群组
     */
    public static void close() {
        for (ChannelGroup group : channelGroups.values()) {
            group.close();
        }
    }

}
